<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
        >新增
        </el-button>
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </div>
      <div class="right-panel">
        <jcx-table-bar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></jcx-table-bar>
      </div>
    </el-header>

    <el-main>
      <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch"
               label-width="108px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="模板分类备注" prop="remark">
              <el-input
                  v-model="queryParams.remark"
                  placeholder="请输入模板分类备注"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模板分类状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择模板分类状态" clearable>
                <el-option key="1" label="启用" :value="true"/>
                <el-option key="0" label="停用" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table ref="table" v-loading="loading" :data="categoryList" row-key="categoryId"
                @selection-change="handleSelectionChange"
                :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="分类标识" align="center" prop="categoryCode" v-if="columns[0].visible"></el-table-column>
        <el-table-column label="分类名称" align="center" prop="categoryName" v-if="columns[1].visible"></el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[2].visible">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">启用</el-tag>
            <el-tag v-if="!scope.row.status" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[3].visible"></el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[4].visible"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="props">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(props.row)"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(props.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <jcx-page
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      ></jcx-page>

      <el-dialog destroy-on-close append-to-body width="1000px" :title="title" v-model="open"
                 :close-on-click-modal="false" @closed="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="分类标识" prop="categoryCode">
                <el-input v-model="form.categoryCode" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="form.categoryName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否有效" prop="status">
                <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" clearable type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-table ref="formTable" v-loading="formLoading" :data="templateList" row-key="templateId"
                    @selection-change="formHandleSelectionChange"
                    highlight-current-row
                    :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="模板标识" align="center" prop="templateCode"></el-table-column>
            <el-table-column label="模板名称" align="center" prop="templateName"></el-table-column>
            <el-table-column label="模板类型" align="center" prop="templateType"></el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-tag v-if="scope.row.status" type="success">启用</el-tag>
                <el-tag v-if="!scope.row.status" type="danger">停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
            <el-table-column label="备注" align="center" prop="remark"></el-table-column>
          </el-table>

          <jcx-page
              v-show="formTotal>0"
              :total="formTotal"
              v-model:page="formQuery.pageNum"
              v-model:limit="formQuery.pageSize"
              @pagination="getFormList"
          ></jcx-page>

        </el-form>
        <template #footer>
          <el-button type="primary" :loading="saveing" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>

export default {
  name: "TemplateCategory",
  data() {
    return {
      // 遮罩层
      loading: true,
      formLoading: true,
      // 保存遮罩层
      saveing: false,
      // 选中数组
      ids: [],
      selectList: {},
      selectOpen: {},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 列表数据
      categoryList: [],
      // 模板列表
      templateList: [],
      selectTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分页总条数
      total: 0,
      formTotal: 0,
      // 查询参数
      queryParams: {
        remark: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10
      },
      formQuery: {
        pageNum: 1,
        pageSize: 5
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryCode: [
          {required: true, message: '分类标识不能为空', trigger: 'blur'}
        ],
        categoryName: [
          {required: true, message: '分类名称不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '状态不能为空', trigger: 'blur'}
        ],
      },
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      columns: [
        {key: 0, label: `分类标识`, visible: true},
        {key: 1, label: `分类名称`, visible: true},
        {key: 2, label: `状态`, visible: true},
        {key: 3, label: `创建时间`, visible: false},
        {key: 4, label: `备注`, visible: true}
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getFormList() {
      let once = this.selectOpen["第" + this.formQuery.pageNum + "页"] ? this.selectOpen["第" + this.formQuery.pageNum + "页"] : 0;
      once++;
      this.selectOpen["第" + this.formQuery.pageNum + "页"] = once;

      let currentList = this.selectList["第" + this.formQuery.pageNum + "页"] ? this.selectList["第" + this.formQuery.pageNum + "页"] : [];
      this.formLoading = true;
      this.$API.template.pageListTemplate.get(this.formQuery).then(response => {
        if (response.status) {
          this.templateList = response.data.records;
          // 处理默认选中
          if (once === 1 && this.selectTemplateList && this.selectTemplateList.length !== 0) {
            this.selectTemplateList.map(item => {
              let flag = false;
              currentList.map(current => {
                if (item.templateId === current.templateId) {
                  flag = true;
                }
              });
              if (!flag) {
                currentList.push(item)
              }
            })
          }
          if (currentList && currentList.length !== 0) {
            // 创建一个空数组用来存放默认数据
            let list = []
            // 遍历表格的数据，再遍历需要在表格中反显的数据，两者的id一致
            this.templateList.forEach((item) => {
              currentList.forEach(val => {
                if (val.templateId === item.templateId) {
                  // 把判断出来的默认表格数据push到创建的数组中
                  list.push(item)
                }
              })
            })
            if (list) {
              this.$nextTick(() => {
                // 再遍历数组，将数据放入方法中
                list.forEach((row, index) => {
                  this.$refs.formTable.toggleRowSelection(row, true)
                });
              });
            }
          }
          this.formTotal = response.data.total;
          this.formLoading = false;
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.$API.category.pageListCategory.get(this.queryParams).then(response => {
        if (response.status) {
          this.categoryList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.templateList = [];
      this.selectTemplateList = [];
      this.selectList = {};
      this.selectOpen = {};
      this.formQuery.pageNum = 1;
      this.formQuery.pageSize = 5;
      this.form = {
        categoryId: "",
        categoryCode: "",
        categoryName: "",
        status: true,
        remark: ""
      };
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    formHandleSelectionChange(selection) {
      let currentList = this.selectList["第" + this.formQuery.pageNum + "页"] ? this.selectList["第" + this.formQuery.pageNum + "页"] : [];
      selection.map(select => {
        let flag = false;
        currentList.map(item => {
          if (item.templateId === select.templateId) {
            flag = true;
          }
        });
        if (!flag) {
          currentList.push(select)
        }
      });
      let newList = [];
      currentList.map(item => {
        let flag = false;
        selection.map(select => {
          if (item.templateId === select.templateId) {
            flag = true;
          }
        });
        if (flag) {
          newList.push(item)
        }
      });
      this.selectList["第" + this.formQuery.pageNum + "页"] = newList
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加分类";
      this.getFormList();
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId || this.ids
      this.$API.category.getCategoryById.get(categoryId).then(response => {
        if (response.status) {
          this.form = response.data;
          this.selectTemplateList = this.form.toolTemplateQueryDtoList
          this.getFormList();
          this.title = "修改分类";
          this.open = true;
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      let array = Object.keys(this.selectList);
      let list = [];
      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < this.selectList[array[i]].length; j++) {
          list.push(this.selectList[array[i]][j]);
        }
      }
      this.form.toolTemplateQueryDtoList = list;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.categoryId) {
            this.$API.category.editCategory.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.category.addCategory.post(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId ? [row.categoryId] : this.ids;
      this.$confirm(`确定删除选中的 ${categoryIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.category.delCategory.delete(categoryIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      })
    },
  }
};
</script>

<style scoped>
</style>
